package com.suyafei.controller;

import com.suyafei.entity.Order;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * @program: springboot-rabbitmq
 * @description
 * @author: luffy
 * @create: 2020-11-14 22:58
 */
@RestController()
public class OrderController {


    @Autowired
    private Order order;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping(value = "/addorder")
    public ModelAndView getAddOrder() {
        ModelAndView modelAndView = new ModelAndView("html/addorder");
        return modelAndView;
    }

    @GetMapping(value = "/pay")
    public ModelAndView addOrder(Model model) throws UnsupportedEncodingException {
        UUID uuid = UUID.randomUUID();
        String orderId = uuid.toString();
        System.out.println("我是orderId：" + orderId);
        order.getOrderIdSet().add(orderId);
        Message msg = MessageBuilder.withBody(orderId.getBytes("utf-8")).build();
        rabbitTemplate.send("ex.pay.ttl-waiting", "pay.ttl-waiting", msg);
        model.addAttribute("orderId", orderId);
        ModelAndView modelAndView = new ModelAndView("html/pay");

        return modelAndView;
    }

    @GetMapping(value = "/finishPay")
    public ModelAndView finishPay(String orderId,Model model) {
        System.out.println(orderId);
        boolean contains = order.getOrderIdSet().contains(orderId);
        if (contains) {
            ModelAndView modelAndView = new ModelAndView("html/success");
            return modelAndView;
        }else{
            model.addAttribute("orderId", orderId);
            ModelAndView modelAndView = new ModelAndView("html/fail");
            return modelAndView;
        }
    }
}
